#!/usr/bin/env groovy
package com.yidao.www
@Grab('com.google.code.gson:gson:2.8.5')
@Grab("org.codehaus.groovy:groovy-json:3.0.4")
import com.google.gson.*;
import groovy.json.*;
def repoSync(manifest_url, repo_url){

}

def gitClone(gitUrl, branch){
    git branch: branch, url: gitUrl
}

// @NonCPS
def gitRepos(gitInfo, branch){
    print gitInfo
    for(git in gitInfo){
        print '============='
        println "git: ${git}"
        print '============='
        def gitUrl = git['url']
        def gitBranch = git['branch']
        def gitTargetDir = git['targetDir']
        gitCheckout(gitUrl, gitBranch, gitTargetDir)
    }
}

def gitlabRepos(gitInfo, branch){
    print gitInfo
    for(git in gitInfo){
        print '============='
        println "git: ${git}"
        print '============='
        def gitUrl = git['url']
        def gitBranch = git['branch']
        def gitTargetDir = git['targetDir']
        gitlabCheckout(gitUrl, gitBranch, gitTargetDir)
    }
}

def submoduleCheckout(gitUrl, gitBranch){
     checkout([
            $class: 'GitSCM',
            branches: [[name: gitBranch]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [
                    $class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: true,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false
                ]
            ],
            submoduleCfg: [],
            userRemoteConfigs: [[credentialsId: 'gitlab_61', url: gitUrl]]
        ])
}

def submoduleGerritCheckout(gitUrl, gitBranch){
     checkout([
            $class: 'GitSCM',
            branches: [[name: gitBranch]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [
                    $class: 'BuildChooserSetting',
                    buildChooser: [
                        $class: 'GerritTriggerBuildChooser'
                    ]
                ],
                [
                    $class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: true,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false
                ]
            ],
            submoduleCfg: [],
            userRemoteConfigs: [[refspec: GERRIT_REFSPEC, url: gitUrl]]
        ])
}

@NonCPS
def gitCheckout(gitUrl, gitBranch, gitTargetDir){
     checkout([
            $class: 'GitSCM',
            branches: [[name: gitBranch]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [
                    $class: 'CleanBeforeCheckout'
                ],
                [
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: gitTargetDir
                ],
                [
                    $class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: true,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false
                ],
                [
                    $class: 'CloneOption',
                    noTags: false,
                    reference: '',
                    shallow: false,
                    timeout: 30
                ]
            ],
            submoduleCfg: [],
            userRemoteConfigs: [[credentialsId: 'gitlab', url: gitUrl]]
        ])
}

@NonCPS
def gitlabCheckout(gitUrl, gitBranch, gitTargetDir){
     checkout([
            $class: 'GitSCM',
            branches: [[name: gitBranch]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [
                    $class: 'CleanBeforeCheckout'
                ],
                [
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: gitTargetDir
                ],
                [
                    $class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: true,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false
                ],
                [
                    $class: 'CloneOption',
                    noTags: false,
                    reference: '',
                    shallow: false,
                    timeout: 30
                ]
            ],
            submoduleCfg: [],
            userRemoteConfigs: [[credentialsId: 'gitlab_61', url: gitUrl]]
        ])
}

@NonCPS
def gerritCheckout(gitUrl, gitBranch, gitTargetDir, gerritRefspec){
     checkout([
            $class: 'GitSCM',
            branches: [[name: gitBranch]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [
                    $class: 'BuildChooserSetting',
                    buildChooser: [
                        $class: 'GerritTriggerBuildChooser'
                    ]
                ],
                [
                    $class: 'CleanBeforeCheckout'
                ],
                [
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: gitTargetDir
                ],
                [
                    $class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: false,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false
                ]
            ],
            submoduleCfg: [],
            userRemoteConfigs: [[refspec: gerritRefspec, url: gitUrl]]
        ])
}

def cherryPick(gitUrl, refspec){
    def script = "git fetch ${gitUrl} ${refspec} && git cherry-pick FETCH_HEAD"
    def status = scriptStatus(script)
    return status
}

def batCherryPick(){
    def script = "git fetch ${gitUrl} ${refspec} && git cherry-pick FETCH_HEAD"
    def status = batScriptStatus(script)
    return status
}

def mavenPackage(pom, profile){
    def mvnCmd
    if(profile){
        mvnCmd = "mvn clean package -f ${pom} -P ${profile} -DskipTests"
    }else{
        mvnCmd = "mvn clean package -f ${pom} -DskipTests"
    }
    scriptStatus(mvnCmd)
}

def mavenDeploy(pom){

}

//maven项目打包
def mavenBuild(pom, profile){
    def server = Artifactory.server 'jfrog-artifactory'
    def rtMaven = Artifactory.newMavenBuild()
    def buildInfo = Artifactory.newBuildInfo()
    String goals
    print profile.getClass()
    if(profile){
        goals = "clean package -P ${profile} -DskipTests"
    }else{
        goals = "clean package -DskipTests"
    }
    rtMaven.deployer releaseRepo: 'Release', snapshotRepo: 'Snapshot', server: server
    rtMaven.run pom: pom, goals: goals, buildInfo: buildInfo
    server.publishBuildInfo buildInfo
}

def npmBuild(buildScript){
    def status = scriptStatus(buildScript)
    return status
}

// def gradleBuild(buildFile){
//     def server = Artifactory.server 'jfrog-artifactory'
//     def rtGradle = Artifactory.newGradleBuild()
//     def buildInfo= Artifactory.newBuildInfo()
//     // rtGradle.useWrapper = true
//     rtGradle.run rootDir: './', buildFile: buildFile, tasks: 'clean war', buildInfo: buildInfo
//     server.publishBuildInfo buildInfo
// }

def gradleBuild(buildFile){
    println buildFile
    sh "gradle clean war"
}

def gradleDeploy(){
    withCredentials([usernamePassword(credentialsId: 'Nexus3', passwordVariable: 'nexusPassword', usernameVariable: 'nexusUser')]) {
        sh "./gradlew publishMavenJavaPublicationToMavenRepository -PnexusUser=${nexusUser} -PnexusPassword=${nexusPassword}"
    }
}

def gradleBuildScript(buildFile, buildTask){
    sh "bash gradlew clean ${buildTask}"
}

def archive(artifact){
    archiveArtifacts artifacts: artifact, followSymlinks: false, onlyIfSuccessful: true
}

//tomcat部署
def tomcatDeploy(project, artifact, artifactName){
    def deployProfile = deployProfile(project)
    def remoteHost = deployProfile.remoteHost
    def remoteUser = deployProfile.remoteUser
    def remoteDir = deployProfile.remoteDir
    def restartScript = deployProfile.restartScript
    print '==============='
    print deployProfile
    print '==============='
    def result = sh(script:"sshpass ssh ${remoteUser}@${remoteHost} ls ${remoteDir}", returnStatus: true)
    if(result != 0){
        echo "[ERROR] Tomcat异常"
    }
    sh "scp ${artifact} ${remoteUser}@${remoteHost}:${remoteDir}"
    println "${restartScript}"
    sh "ssh ${remoteUser}@${remoteHost} ${restartScript}"
}

//后端maven项目部署
def mavenDeploy(project, artifact, artifactName){
    def deployProfile = deployProfile(project)
    def remoteHost = deployProfile.remoteHost
    def remoteUser = deployProfile.remoteUser
    def remotePWD = env.platformPWD
    def remoteDir = deployProfile.remoteDir
    def bakFormat = deployProfile.backupFormat
    print '==============='
    print deployProfile
    print '==============='
    def result = sh(script:"sshpass ssh ${remoteUser}@${remoteHost} ls ${remoteDir}/${artifactName}", returnStatus: true)
    if(result == 0){
        sh "sshpass ssh ${remoteUser}@${remoteHost} 'cp ${remoteDir}/${artifactName} ${remoteDir}/${artifactName}${bakFormat}'"
    }
    sh "sshpass scp ${artifact} ${remoteUser}@${remoteHost}:${remoteDir}"
    sh "sshpass ssh ${remoteUser}@${remoteHost} ${remoteDir}/bin/start.sh"
}

//前端项目部署
def webDeploy(project, artifact, artifactName){
    def deployProfile = deployProfile(project)
    def remoteHost = deployProfile.remoteHost
    def remoteUser = deployProfile.remoteUser
    def remotePWD = env.platformPWD
    def remoteDir = deployProfile.remoteDir
    def bakFormat = deployProfile.bakFormat
    print '==============='
    print deployProfile
    print remoteHost
    print remoteUser
    print remoteDir
    print bakFormat
    print '==============='
    def result = sh(script: "sshpass ssh ${remoteUser}@${remoteHost} ls ${remoteDir}/${artifactName}", returnStatus: true)
    if(result ==0){
        sh "sshpass ssh ${remoteUser}@${remoteHost} 'cp -r ${remoteDir}/${artifactName} ${remoteDir}/${artifactName}${bakFormat}'"
    }
    sh "sshpass scp -r ${artifact} ${remoteUser}@${remoteHost}:${remoteDir}"
}

//artifactory上传文件
@NonCPS
def fileUpload(artifact, targetFolder){
    def server = Artifactory.server 'jfrog-artifactory'
    def uploadSpec = """{
        "files": [
         {
             "pattern": "${artifact}",
             "target": "${targetFolder}"
         }
        ]
    }"""
    server.upload spec: uploadSpec
}

// @NonCPS
def multiFilesUpload(artifacts, targetFolder){
    println 'artifacts: ' + artifacts
    for(artifact in artifacts){
        fileUpload(artifact, targetFolder)
    }
}

@NonCPS
def fileDownload(artifact, targetFolder){
    def server = Artifactory.server 'jfrog-artifactory'
    def downloadSpec = """{
        "files": [
         {
             "pattern": "${artifact}",
             "target": "${targetFolder}",
             "flat": "true"
         }
        ]
    }"""
    server.download spec: downloadSpec
}

def downloadFile(artifact, targetFolder){
    def server = Artifactory.server 'jfrog-artifactory'
    def downloadSpec = """{
        "files": [
         {
             "pattern": "${artifact}",
             "target": "${targetFolder}",
             "flat": "true"
         }
        ]
    }"""
    server.download spec: downloadSpec
}

def backupFolder(prefix, project, branch, buildDate){
    def date = buildDate.format("yyyyMMdd")
    def year = buildDate.format("yyyy")
    def month = buildDate.format("MM")
    def day = buildDate.format("dd")
    def time = buildDate.format("HHmmss")
    currentBuild.displayName = date + time
    folder = prefix + '/' + branch + '/' + year + '/' + month + '/' + day + '/' + time + '/'
    // def folder = prefix + '/' + branch + '/' + date + '/' + time + '/'
    return folder
}

def mvnSonarScan(project, version){
    withSonarQubeEnv('Sonar') {
        sh "mvn compile -Dsonar.projectKey=${project} -Dsonar.projectName=${project} -Dsonar.projectVersion=${version} -Dsonar.sourceEncoding=UTF-8 -Dsonar.java.binaries=target/classes"
    }
}

def cppckeckSonarScan(project, version, workDir){
    withSonarQubeEnv('Sonar') {
        sh """
            cppcheck --enable=all . --inconclusive --xml --xml-version=2 ${workDir} 2> ./cppcheck.xml
            ${scanner}/bin/sonar-scanner -Dsonar.projectKey=${project} -Dsonar.projectName=${project} -Dsonar.projectVersion=${version} -Dsonar.inclusions=**/**.cpp,**/**.h,**/**.cc -Dsonar.sources=.
        """
    }
}

def scriptStatus(script){
    def status = sh(returnStatus: true, script: script)
    return status
}

def scriptStdout(script){
    // def script = "ls ${artifactory}"
    def stdout = sh(returnStdout: true, script: script).trim()
    return stdout
}

def batScriptStatus(script){
    def status = bat(returnStatus: true, script: script)
    return status
}

def batScriptStdout(script){
    def stdout = bat(returnStdout: true, script: script).trim()
    return stdout
}

def cherryPickFailClean(){
    def script = "git reset --hard && git clean -df"
    scriptStatus(script)
}

def batCherryPickFailClean(){
    def script = "git reset --hard && git clean -df"
    batScriptStatus(script)
}

def cherryPickClean(){
    def script = "git reset --hard HEAD^ && git clean -df"
    scriptStatus(script)
}

def jsonFormat(json){
    JsonParser jsonParser = new JsonParser()
    JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject()
    Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
    return gson.toJson(jsonObject)
}

def map2JsonStr(map){
    Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
    def json = gson.toJson(map)
    return json
}

def str2JsonObject(jsonStr){
    JsonParser jsonParser = new JsonParser()
    JsonObject jsonObject = jsonParser.parse(jsonStr).getAsJsonObject()
    return jsonObject
}

def writeFile(content, filePath){
    writeFile file: filePath, text: content, encoding: "UTF-8"
}

def readJson(content){
    def json = readJSON text: content
    return json
}

def viewFiles(filePath){
    File file = new File(filePath)
    if(file.isDirectory()){
        def files = file.list()
        print files.length
        for(f in files){
            print 'file: ' + f
        }
        if(files.length > 0){
            return true
        }else{
            return false
        }
    }else{
        throw new Exception("${filePath} 不是目录!")
    }
}

def generateConfigJson(robot, number, version, branch){

    def robotDeployProfile = robotDeployProfile(robot, number, version, branch)
    String username //= robotDeployProfile.username
    String password //= robotDeployProfile.password
    int port// = robotDeployProfile.port
    def devices = robotDeployProfile.devices
    String device
    String ip
    Boolean using_sftp
    String local_package
    String remote_package
    Boolean using_ssh
    String update_cmd
    int chip_no
    Boolean using_serial
    String file

    def steps = [:]
    def list = []
    devices.each {
        device = it.key
        value = it.value
        user = value.user
        password = value.password
        ip = value.ip
        port = value.port
        using_sftp = value.using_sftp
        local_package = value.local_package
        remote_package = value.remote_package
        using_ssh = value.using_ssh
        update_cmd = value.update_cmd
        chip_no = value.chip_no
        using_serial = value.using_serial
        file = value.file
        def map = [:]
        map['device'] = device
        map['user'] = user
        map['password'] = password
        map['ip'] = ip
        map['port'] = port
        map['using_sftp'] = using_sftp
        map['local_package'] = local_package
        map['remote_package'] = remote_package
        map['using_ssh'] = using_ssh
        map['update_cmd'] = update_cmd
        map['chip_no'] = chip_no
        map['using_serial'] = using_serial
        map['file'] = file
        list.add(map)
    }
    steps['steps'] = list
    def json = map2JsonStr(steps)
    return json
}

def influxDb(){
    influxDbPublisher selectedTarget: 'InfluxDB'
}

def zipPackage(zipFile, directory){
    println zipFile
    println directory
    zip dir: directory, glob: '', zipFile: zipFile
    // sh "zip ${zipFile} ${directory}"
}

def unZipPackage(zipFile, directory){
    unzip dir: directory, glob: '', zipFile: zipFile
}

def cpplintCheck(checkName, recordFile){
    def script = "cpplint --extensions=cpp,cxx,h --filter=-whitespace --recursive ${checkName} 2>&1 | tee ${recordFile}"
    def status = scriptStatus(script)
    return status
}

@NonCPS
def recordIssues(reportFile){
    recordIssues(tools: [cppLint(pattern: 'cpplint-result.xml', reportEncoding: 'UTF-8')])
}

def queryNewIssues(buildUrl){
    def script = "curl -X POST ${buildUrl}cpplint/new/api/json --user changbin:110c39657bc8cef11e8d77d9b43173cc1e"
    def result = scriptStdout(script)
    def resultJson = readJson(result)
    return resultJson
}

def copyArtifacts(project, target){
    copyArtifacts fingerprintArtifacts: true, projectName: project, selector: lastSuccessful(), target: target
}

def playbook(tag){
    ansiblePlaybook disableHostKeyChecking: true, installation: 'ansible-playbook', inventory: 'playbook/hosts', playbook: 'playbook/site.yml', tags: tag
}
